﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace CommonUtil
{
    public class SerializeUtil
    {
        /// <summary>
        /// 序列化-对象到字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string SerializeObject<T>(T obj)
        {
            try
            {
                IFormatter ifmt = new BinaryFormatter();
                MemoryStream mstream = new MemoryStream();
                ifmt.Serialize(mstream, obj);
                mstream.Position = 0;
                byte[] buffer = new byte[mstream.Length];
                mstream.Read(buffer, 0, buffer.Length);
                mstream.Flush();
                mstream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception("序列化失败，原因：" + ex.Message);
            }
        }

        /// <summary>
        /// 反序列化-字符串到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">泛型对象</param>
        /// <param name="objString">要转换为对象的字符串</param>
        /// <returns>反序列化出来的对象</returns>
        public static T DesrializeObject<T>(T obj, string objString)
        {
            try
            {
                obj = default(T);
                IFormatter ifmt = new BinaryFormatter();
                byte[] buffer = Convert.FromBase64String(objString);
                MemoryStream mstream = new MemoryStream(buffer);
                obj = (T)ifmt.Deserialize(mstream);
                mstream.Flush();
                mstream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("反序列化失败，原因：" + ex.Message);
            }
            return obj;
        }
    }
    /*
     * Example :
     * 
    //序列化
    Args args = new Args();
    string result = SerializeObject(dt);

    //反序列化
    Args args  = new Args();
    string argsString = result;
    args = (Args)DesrializeObject(args,argsString);
    */
}
